<?php

namespace App\Models\System;

use App\Components\Redis;
use Illuminate\Database\Eloquent\Model;

class SystemConfig extends Model
{
    protected $table = 'system_config';

    public static function getConfig(string $type)
    {
        $cacheKey = 'MODELS:SYSTEM:SYSTEMCONFIG:GET:' . $type;
        $cacheRs = Redis::get($cacheKey);
        if ($cacheRs !== false && $cacheRs !== null) {
            return json_decode($cacheRs, true);
        }

        $listRs = self::select('id', 'name', 'content')
            ->where('type', $type)
            ->orderBy('id', 'asc')->get()->toArray();
        if (!isset($listRs[0]['id'])) {
            return [];
        }
        $return = [];
        foreach ($listRs as $v) {
            $return[$v['name']] = $v['content'];
        }
        unset($listRs);

        Redis::setex($cacheKey, Redis::mediumTime(), json_encode($return));

        return $return;
    }

    public static function clearConfigCache(string $type)
    {
        $cacheKey = 'MODELS:SYSTEM:SYSTEMCONFIG:GET:' . $type;
        Redis::del($cacheKey);
        return true;
    }
}
